package com.ithuameng.notice.task;

import com.ithuameng.notice.model.MessageLog;
import com.ithuameng.notice.service.IMessageLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MessageSendTask {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IMessageLogService messageLogService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void messageSendTask() {
        List<MessageLog> logs = messageLogService.getByStatus();
        if (logs.size() == 0) {
            return;
        }
        logs.forEach(item -> {
            if (item.getCount() >= 3) {
                // 消息发送失败
                messageLogService.updateStatus(item.getMsgId(), 2);
            } else {
                // 更新重试数量
                messageLogService.updateCount(item.getMsgId());
                // 发送消息   内容不作重点演示
                rabbitTemplate.convertAndSend("system_notice_exchange", null, "message", new CorrelationData(item.getMsgId()));
            }
        });
    }
}
